package cn.leven.web.response;

import cn.leven.utils.DownLoadUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Random;

/**
 *  文件下载
*/
@WebServlet("/rdct5")
public class RedirectDemo5 extends HttpServlet {
    protected void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException {
        String fileName = req.getParameter("filename"); // 获取参数
        ServletContext servletContext = this.getServletContext();
        String s =  servletContext.getRealPath("/img/" +fileName); //  获取文件地址
        FileInputStream fileInputStream = new FileInputStream(s); // 输入流

        String mime =  servletContext.getMimeType(fileName);// 获取文件类型
        res.setContentType(mime);

        String agent = req.getHeader("user-agent"); // 获取浏览器
        fileName = DownLoadUtils.getFileName(agent,fileName); // 编码文件名解决下载名乱码问题

        res.setHeader("content-disposition","attachment;filename="+fileName); // 告诉浏览器处理的方式是下载

        ServletOutputStream servletOutputStream = res.getOutputStream();//设置输出流
        byte[] buff = new byte[1024*8];
        int len = 0;
        while ((len = fileInputStream.read(buff))!=-1){
            servletOutputStream.write(buff,0,len);
        };
        fileInputStream.close();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        this.doPost(req,res);
    }
}
